package bot;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;

import org.jibble.pircbot.PircBot;

import administration.Masters;

import commands.Command;
import commands.Leave;
import commands.Lmod;
import commands.Quit;
import commands.Time;

public class MyBot extends PircBot {
	public static final String prefix = ":";
	HashMap<String, Command> commands = new HashMap<String, Command>();
	Masters master;

	public Masters getMaster() {
		return master;
	}

	public MyBot() {
		initConfig();
		master = new Masters();
	}

	private void initConfig() {
		try {
			this.setAutoNickChange(true);
			Properties properties = new Properties();
			properties.load(new FileInputStream("config.ini"));
			setName(properties.getProperty("botname", "ciibot"));
			setVersion(properties.getProperty("botversion", "ciibot"));
			setFinger(properties.getProperty("botfigner", "Take your hands off me!"));
			setLogin(properties.getProperty("botlogin", "ciibot.owns"));
			connect(properties.getProperty("defaultserver", "irc.se.quakenet.org"));
			joinChannel(properties.getProperty("homechannel", "#cii"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e){
			e.printStackTrace();
		}
	}

	public void onMessage(String channel, String sender, String login,
			String hostname, String message) {
		if(message.startsWith(prefix)){
			message = message.replaceFirst( prefix, "" );
			for (Command command : commands.values()){
				if(message.startsWith(command.getCommandName())){
					command.execCommand(channel, sender, login, hostname, message.replaceFirst(command.getCommandName(), "").trim(), this);
				}
			}
		}
	}

	public void onInvite(String targetNick, String sourceNick,
			String sourceLogin, String sourceHostname, String channel) {
		if (master.checkMaster(sourceLogin)) {
			System.out.println(channel);
			String[] list = channel.split(targetNick);

			this.joinChannel(list[list.length - 1]);
		}
	}

	public HashMap<String, Command> getCommands() {
		return commands;
	}

	public static void main(String[] args) throws Exception {
		MyBot bot = new MyBot(); // Now start our bot up.
		bot.setVerbose(true); // Enable debugging output.
		loadStartMods(bot);
	}

	public static void loadStartMods(MyBot bot) {
		bot.getCommands().put("Lmod", new Lmod());
		bot.getCommands().put("Quit", new Quit());
		bot.getCommands().put("Leave", new Leave());
		bot.getCommands().put("Time", new Time());
	}

}
